package cn.yunyichina.provider.authorize.service.impl;

import cn.yunyichina.provider.authorize.entity.Api;
import cn.yunyichina.provider.authorize.service.ApiService;
import cn.yunyichina.provider.framework.dubbo.service.BaseService;
import cn.yunyichina.provider.framework.dubbo.service.CacheService;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.provider.iface.entity.common.ResponseObject;
import cn.yunyichina.utils.commons.StringUtils;
import cn.yunyichina.utils.convert.JsonUtils;
import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by kevin on 2017/10/14.
 */
@Service
public class ApiServiceImpl implements ApiService {

    private static final Logger logger = LoggerFactory.getLogger(ApiServiceImpl.class);


    @Override
    public ResponseObject reloadApi(String data) {
        ResponseObject response = new ResponseObject();
        response.setResultCodeAndMessage("9009","init fail");

        Response apiResponse= BaseService.callUnderlineFromInternal("yyt.base.api.list", "");
        String resultStr=apiResponse.getResult();
        if(StringUtils.isBlank(resultStr)){
            response.setResultCodeAndMessage("9009","data empty");
            return response;
        }

        List<Api> apis= JSON.parseArray(resultStr,Api.class);
        logger.info("redis缓存重新加载api条数:"+apis.size());
        for(Api api:apis){
            CacheService.getCacheClient().setApiCache(api.getApiDefine(), JsonUtils.toJsonString(api));
        }
        response.setResultCodeAndMessage("0","重新加载成功!");
        return response;
    }

    @Override
    public ResponseObject deleteApi(String key) {
        ResponseObject response = new ResponseObject();
        response.setResultCodeAndMessage("0","sucessful");
        CacheService.getCacheClient().deleteApiCache(key);
        return response;
    }
}
